﻿using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace hello_accinv_New_
{
    public partial class SaleForm : Form
    {
        private Database db;
        private int stockQty;

        public SaleForm()
        {
            InitializeComponent();

            db = new Database();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Dispose();
        }

        private void linklbChooseProduct_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            LoadChooseProductDialog();
        }

        private void LoadChooseProductDialog()
        {
            ChooseProductForm choose = new ChooseProductForm();
            if (choose.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtboxSalePCode.Text = choose.selectedProductCode;
            }
            choose.Dispose();
        }

        private void txtboxSalePCode_TextChanged(object sender, EventArgs e)
        {
            if (txtboxSalePCode.Text.Length == 6)
            {
                DataTable dt = db.Select("P.Name, C.Name, P.UnitPrice, P.Quantity", "Product P INNER JOIN Category C ON P.CategoryID = C.CategoryID", "P.Flag = '1' AND P.PCode = '" + txtboxSalePCode.Text + "'");
                // If Product Code is correct.
                if (dt.Rows.Count == 1)
                {
                    txtboxName.Text = dt.Rows[0][0].ToString();
                    txtboxCategory.Text = dt.Rows[0][1].ToString();
                    txtboxPrice.Text = dt.Rows[0][2].ToString();
                    stockQty = Int32.Parse(dt.Rows[0][3].ToString());

                    txtboxDiscount.Text = "0.00";
                    txtboxQuantity.Enabled = true;
                    txtboxQuantity.Focus();
                    txtboxQuantity.Select(0, 1);
                    btnDiscount.Enabled = true;
                    btnRemark.Enabled = true;
                }
                else
                {
                    txtboxSalePCode.ForeColor = Color.Red;
                }
                dt = null;
            }
            else
            {
                // Clear sale form
                txtboxName.Clear();
                txtboxCategory.Clear();
                txtboxPrice.Clear();
                txtboxDiscount.Clear();
                txtboxQuantity.Value = 0;
                txtboxRemark.Clear();

                txtboxQuantity.Enabled = false;
                btnDiscount.Enabled = false;
                btnRemark.Enabled = false;

                txtboxSalePCode.ForeColor = Color.Black;
            }
        }

        private void datagridSaleProductList_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            if (datagridSaleProductList.RowCount > 0)
            {
                // Enable Payment and Cancel buttons
                btnSalePayment.Enabled = true;
                btnSaleCancel.Enabled = true;

                // Calculate Total Price, Total Discount, Total VAT
                UpdatePricePanel();

                // Re-run number
                ReRunNumber();
            }
            else
            {
                // Disable Payment and Cancel buttons
                btnSalePayment.Enabled = false;
                btnSaleCancel.Enabled = false;

                txtboxTotalPrice.Text = "0.00";
                txtboxTotalDiscount.Text = "0.00";
                txtboxTotalVAT.Text = "0.00";
            }
        }

        private void UpdatePricePanel()
        {
            decimal totalP, totalD, totalV; totalP = totalD = totalV = 0;

            // Total Price and Total Discount
            for (int i = 0; i < datagridSaleProductList.RowCount; i++)
            {
                totalP += Decimal.Parse(datagridSaleProductList[6, i].Value.ToString());
                totalD += Decimal.Parse(datagridSaleProductList[5, i].Value.ToString());
            }

            // Total VAT
            totalV = totalP * 0.07M;

            txtboxTotalPrice.Text = totalP.ToString("#,#0.00#");
            txtboxTotalDiscount.Text = totalD.ToString("#,#0.00#");
            txtboxTotalVAT.Text = totalV.ToString("#,#0.00#");
        }

        private void ReRunNumber()
        {
            for (int i = 1; i <= datagridSaleProductList.RowCount; i++)
            {
                datagridSaleProductList[0, (i - 1)].Value = i;
            }
        }

        private void txtboxQuantity_ValueChanged(object sender, EventArgs e)
        {
            if (txtboxQuantity.Value != 0M)
            {
                btnAddToList.Enabled = true;
            }
            else
            {
                btnAddToList.Enabled = false;
            }
        }

        private void SaleForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (datagridSaleProductList.RowCount > 0)
            {
                if (MessageBox.Show("In Progress, Cancel?", "Sale", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                    == System.Windows.Forms.DialogResult.No)
                {
                    e.Cancel = true;
                }
            }
        }

        private void btnDiscount_Click(object sender, EventArgs e)
        {
            DiscountForm discount = new DiscountForm();
            discount.txtboxProduct.Text = txtboxName.Text;
            discount.txtboxPrice.Text = txtboxPrice.Text;
            if (discount.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtboxDiscount.Text = discount.txtboxDiscountBaht.Text;
            }
            discount.Dispose();
        }

        private void btnAddToList_Click(object sender, EventArgs e)
        {
            DoAddProductToList();
        }

        private void datagridSaleProductList_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            // Remove product
            if (e.ColumnIndex == 8)
            {
                if (MessageBox.Show("Remove?", "Remove", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                {
                    datagridSaleProductList.Rows.RemoveAt(e.RowIndex);
                }
            }
        }

        private void btnSaleCancel_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Cancel?", "Cancel", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                txtboxSalePCode.Clear();

                // Remove all datagridview rows
                int rowCount = datagridSaleProductList.RowCount;
                for (int i = 0; i < rowCount; i++)
                {
                    datagridSaleProductList.Rows.RemoveAt(0);
                }

                txtboxSalePCode.Focus();
            }
        }

        private void btnRemark_Click(object sender, EventArgs e)
        {
            AddRemarkForm remark = new AddRemarkForm();
            remark.txtboxRemark.Text = txtboxRemark.Text;
            if (remark.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtboxRemark.Text = remark.txtboxRemark.Text;
            }
            remark.Dispose();
        }

        private void btnSalePayment_Click(object sender, EventArgs e)
        {
            DoPayment();
        }

        private void DoPayment()
        {
            PaymentForm payment = new PaymentForm();
            payment.txtboxTotalPrice.Text = txtboxTotalPrice.Text;
            payment.ShowDialog();
            payment.Dispose();
        }

        private void txtboxQuantity_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((Keys)e.KeyChar == Keys.Enter)
            {
                if(txtboxQuantity.Value > 0)
                    DoAddProductToList();
            }
        }

        private void DoAddProductToList()
        {
            // Check stock quantity
            if (txtboxQuantity.Value > stockQty)
            {
                MessageBox.Show("Insufficient product in stock", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                datagridSaleProductList.Rows.Add(new object[] {
                    "",
                    txtboxSalePCode.Text,
                    txtboxName.Text,
                    txtboxQuantity.Value,
                    txtboxPrice.Text,
                    txtboxDiscount.Text,
                    (Decimal.Parse(txtboxPrice.Text) - Decimal.Parse(txtboxDiscount.Text)) * txtboxQuantity.Value,
                    txtboxRemark.Text
                });
                datagridSaleProductList.ClearSelection();
                txtboxSalePCode.Clear();
                txtboxSalePCode.Focus();
            }
        }

        private void txtboxSalePCode_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.F8:
                    if (datagridSaleProductList.RowCount > 0)
                        DoPayment();
                    break;
            }
        }
    }
}
